<?php

namespace App\Http\Middleware;

use Closure;
use Exception;
use Illuminate\Http\Request;
use mszl\api\utils\ApiUtils;
use Symfony\Component\HttpFoundation\Response;

class ResponseMini
{
    /**
     * 处理传入请求。
     *
     * @param Closure(Request): (Response) $next
     * @throws Exception
     */
    public function handle(Request $request, Closure $next):\Illuminate\Http\Response
    {

        $start = microtime(true);
        $data =  $next($request);

        $content = json_decode($data->getContent(), true);
        if (json_last_error()) {
            $content = $data->getContent();
        }

        if (is_array($content) && isset($content['code'])) return $data;
        if ($content === '') $content = null;
        //after
        $execTime = microtime(true) - $start;

        return response(ApiUtils::success($content, 'success execution:' . number_format($execTime, 5)));
    }

    /**
     * 在响应发送到浏览器后处理任务。
     */
    public function terminate(Request $request, Response $response): void
    {

    }
}
